package com.haohan.jingyuan.sys.service;

import com.haohan.jingyuan.common.constants.CacheConstants;
import com.haohan.jingyuan.sys.dao.DictInfoMapper;
import com.haohan.jingyuan.sys.dto.req.QueryDictListRequest;
import com.haohan.jingyuan.sys.dto.resp.DictInfoResp;
import com.haohan.jingyuan.sys.dto.resp.DictListResp;
import com.haohan.jingyuan.sys.dto.resp.DictTreeResp;
import com.haohan.jingyuan.sys.entity.DictInfo;
import com.haohan.jingyuan.sys.helper.DictInfoRespHelper;
import com.haohan.jingyuan.util.CacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 字典服务实现类
 *
 * @ClassName DictService
 * @Description 字典相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/01/19 14:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DictService {

    /**
     * 字典信息Mapper
     */
    private final DictInfoMapper dictInfoMapper;

    /**
     * 缓存工具
     */
    private final CacheUtil cacheUtil;

    /**
     * 查询字典平铺列表
     *
     * @param request 查询字典列表请求
     * @return 字典平铺列表响应
     */
    public DictListResp queryDictList(QueryDictListRequest request) {
        // 查询字典列表
        List<DictInfo> dictInfoList = dictInfoMapper.selectByType(request.getType(), request.getParentCode());

        // 转换为响应对象
        List<DictInfoResp> dictRespList = DictInfoRespHelper.convert2DictInfoRespList(dictInfoList);

        // 构建响应对象
        DictListResp response = new DictListResp();
        response.setDictList(dictRespList);
        response.setDictType(request.getType());
        response.setParentCode(request.getParentCode());
        response.setTotal(dictRespList.size());
        return response;
    }

    /**
     * 查询字典树形结构
     *
     * @param request 查询字典列表请求
     * @return 字典树形结构响应
     */
    public List<DictTreeResp> queryDictTree(QueryDictListRequest request) {
        // 查询所有字典数据
        List<DictInfo> allDictList = dictInfoMapper.selectTreeByType(request.getType(), null);

        // 构建树形结构
        List<DictTreeResp> treeList = buildTreeStructure(allDictList, request.getParentCode());
        return treeList;
    }

    /**
     * 构建树形结构
     *
     * @param allDictList    所有字典数据
     * @param rootParentCode 根节点的父级字典键
     * @return 树形结构列表
     */
    private List<DictTreeResp> buildTreeStructure(List<DictInfo> allDictList, String rootParentCode) {
        if (CollectionUtils.isEmpty(allDictList)) {
            return new ArrayList<>();
        }

        // 转换为树形响应对象
        List<DictTreeResp> treeRespList = DictInfoRespHelper.convert2DictTreeRespList(allDictList);

        // 构建父子关系映射
        Map<String, List<DictTreeResp>> parentChildMap = new HashMap<>();
        for (DictTreeResp dictResp : treeRespList) {
            String parentCode = dictResp.getParentCode();
            if (parentCode == null || parentCode.trim().isEmpty()) {
                parentCode = "ROOT";
            }

            parentChildMap.computeIfAbsent(parentCode, k -> new ArrayList<>()).add(dictResp);
        }

        // 递归构建树形结构
        List<DictTreeResp> rootList = new ArrayList<>();
        String rootKey = (rootParentCode == null || rootParentCode.trim().isEmpty()) ? "ROOT" : rootParentCode;

        List<DictTreeResp> rootNodes = parentChildMap.get(rootKey);
        if (!CollectionUtils.isEmpty(rootNodes)) {
            for (DictTreeResp rootNode : rootNodes) {
                buildChildren(rootNode, parentChildMap);
                rootList.add(rootNode);
            }
        }

        return rootList;
    }

    /**
     * 递归构建子节点
     *
     * @param parentNode     父节点
     * @param parentChildMap 父子关系映射
     */
    private void buildChildren(DictTreeResp parentNode, Map<String, List<DictTreeResp>> parentChildMap) {
        List<DictTreeResp> children = parentChildMap.get(parentNode.getDictKey());
        if (!CollectionUtils.isEmpty(children)) {
            for (DictTreeResp child : children) {
                buildChildren(child, parentChildMap);
                parentNode.getChildren().add(child);
            }
        }
    }

    /**
     * 查询所有行业类型字典（带缓存）
     *
     * @return 行业类型字典Map，key为dictKey，value为dictValue
     */
    @SuppressWarnings("unchecked")
    public Map<String, String> getAllIndustryType() {
        String cacheKey = CacheConstants.CACHE_INDUSTRY_TYPE;
        Map<String, String> cachedMap = cacheUtil.get(cacheKey, Map.class);
        if (cachedMap != null) {
            return cachedMap;
        }

        // 从数据库查询
        List<DictInfo> industryList = dictInfoMapper.selectAllByType("industryType");
        
        // 转换为Map，key为dictKey，value为dictValue
        Map<String, String> industryMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(industryList)) {
            for (DictInfo dictInfo : industryList) {
                industryMap.put(dictInfo.getDictKey(), dictInfo.getDictValue());
            }
        }
        
        // 存入缓存，缓存24小时
        cacheUtil.put(cacheKey, industryMap, 24, TimeUnit.HOURS);
        
        return industryMap;
    }
}
